<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CompanyController
 *
 * @author admin
 */

namespace Admin\Controller;

use Home\ORG\Str;
use Think\Exception;
class ProductController extends BaseController {
    //put your code here

    function Index() {
        $configuration  = D('ApiConfiguration ')->select();
        $config=unserialize($configuration[0]['configuration']);
        //print_r($config);

        $companyId = (int)I('get.cid');
        if(!$companyId){
            throw new Exception('无效的企业编号');
        }
        //$list = D('ApiProduct')->where(array('company_id'=>$companyId))->select();
        $list = D('api_product')
            ->join('api_company on api_company.id = api_product.company_id')
            ->field('api_product.*,api_company.company_name,api_company.id as company_id')
            ->where('api_product.company_id = '.$companyId)->select();


        $productList = $this->buildArrByNewKey($list);

        $this->assign('list', $productList);
        $this->assign('companyId', $companyId);
        $this->display();

    }
    function Add() {
        if (IS_POST) {
            $data = I('post.');
            $has = D('ApiProduct')->where(array('product_name' => $data['product_name']))->count();
            if ($has) {
                $this->ajaxError('此产品已经存在，请重设！');
            }
            /*
            $data['password'] = user_md5($data['password']);
            $data['regIp'] = get_client_ip(1);
            $data['regTime'] = time();
             *
             */
            $data['valid_date'] = strtotime($data['valid_date']);
            $data['app_code'] = D('ApiProduct')->newAppCode($data['app_code']);

            $configurationName  = D('ApiConfiguration ')->where("id=1")->find();
            $config=unserialize($configurationName['configuration']);
            $id=$data['configuration_id'];
            $contents = array_chunk($data['content'],count($config[$id]['content']));
            $str = '';
            foreach($contents as $k=>$v){
                $str .= implode('-',$v)."*";
            }
            $data['auth_content'] = trim($str,'*');
            $res = D('ApiProduct')->add($data);
            if ($res === false) {
                $this->ajaxError('操作失败');
            } else {
                $this->ajaxSuccess('添加成功');
            }
        } else {
            $detail = array();
            $detail['app_code'] = D('ApiProduct')->newAppCode();
            $detail['valid_date'] = time();
            $companyId = I('get.cid');
            $companyInfo = D('ApiCompany')->find($companyId);
            if(!$companyInfo){
                throw new Exception('无效的企业信息，请从企业页面点击管理产品。');
            }
            $detail['company_id'] = $companyInfo['id'];
            $detail['company_name'] = $companyInfo['company_name'];

            //下拉框配置选项
            $configuration  = D('ApiConfiguration ')->where("id=1")->find();
            $config=unserialize($configuration['configuration']);
            $new = array();
            foreach ($config as $k =>$v){
                $new[$k]['id']=$v['id'];
                $new[$k]['title']=$v['title'];
                $new[$k]['count']=count($v['content']);
            }
            foreach ($config as $key =>$value){
                foreach($value['content'] as $k => $v){
                    $styles[$key][$k]['name']=$v['name'];
                    $styles[$key][$k]['length']=$v['length'];
                    $styles[$key][$k]['type']=$v['type'];
                }
            }
            foreach ($styles as $key => $value) {
                $data[$key]['name'] = implode('#',array_column($value,'name'));
                $data[$key]['length'] = implode('#',array_column($value,'length'));
                $data[$key]['type'] = implode('#',array_column($value,'type'));
            }
            $arr=array();
            foreach($new as $k => $v){
                $arr[] = array_merge($v,$data[$k]);
            }

            $this->assign('detail',$detail);
            $this->assign('configuration',$arr);
            $this->display();
        }

    }
    function edit() {
        if (IS_POST) {
            $data = I('post.');
            $has = D('ApiProduct')->where(array('product_name' => $data['product_name']))->where(' id != '.$data['id'])->count();
            if ($has) {
                $this->ajaxError('此公司已经存在，请重设！');
            }
            /*
            $data['password'] = user_md5($data['password']);
            $data['regIp'] = get_client_ip(1);
            $data['regTime'] = time();
             *
             */
        
            unset($data['app_code']);
            $data['valid_date'] = strtotime($data['valid_date']);

            $configuration  = D('ApiConfiguration ')->where("id=1")->find();
            $config=unserialize($configuration['configuration']);
            $id=$data['configuration_id'];
            $contents=array_chunk($data['content'],count($config[$id]['content']));

            $str = '';
            foreach($contents as $k=>$v){
                $str .= implode('-',$v)."*";
            }
            $data['auth_content'] = trim($str,'*');

            $res = D('ApiProduct')->save($data);
            if ($res === false) {
                $this->ajaxError('操作失败');
            } else {
                if( $res != '0' ) D('ApiProduct')->where("id='".$data['id']."'")->save(array('auth_crypt'=>''));
                $this->ajaxSuccess('添加成功');
            }
        } else {
            $id = (int)I('get.id');
            $detail = D('api_product')
                ->join('api_company on api_company.id = api_product.company_id')
                ->field('api_product.*,api_company.company_name')
                ->where('api_product.id = '.$id)->find();
            if(!$detail){
                throw new Exception('无效的产品信息。');
            }

            //$companyId = I('get.cid');
            /*
            $companyInfo = D('ApiCompany')->find($companyId);
            $detail['company_name'] = $companyInfo['company_name'];
            */
    
            $configuration  = D('ApiConfiguration ')->where("id=1")->find();
            $config=unserialize($configuration['configuration']);
            $conf_id=$detail['configuration_id'];
            $configContent=$config[$conf_id]['content'];
            //下拉框配置选项
            $new = array();
            foreach ($config as $k =>$v){
                $new[$k]['id']=$v['id'];
                $new[$k]['title']=$v['title'];
                $new[$k]['count']=count($v['content']);
            }

             foreach ($config as $key =>$value){
                foreach($value['content'] as $k => $v){
                    $styles[$key][$k]['name']=$v['name'];
                    $styles[$key][$k]['length']=$v['length'];
                    $styles[$key][$k]['type']=$v['type'];
                }
            }
            
            foreach ($styles as $key => $value) {
                $data[$key]['name'] = implode('#',array_column($value,'name'));
                $data[$key]['length'] = implode('#',array_column($value,'length'));
                $data[$key]['type'] = implode('#',array_column($value,'type'));
            }
            $arr=array();
            foreach($new as $k => $v){
                $arr[] = array_merge($v,$data[$k]);
            }

            $name = array_column($configContent,'name');
            $length = array_column($configContent,'length');
            $type = array_column($configContent,'type');
            $j = 1;
            if (!empty($detail['auth_content'])) {
                $content = explode('*',$detail['auth_content']);
                foreach ($content as $k => $v) {
                    $contents = explode('-',$v);
                    $str .= "<span>";
                    for($i=0;$i<count($configContent);$i++){
                        $str .= $name[$i].'：<input type="'.$type.'" name="content['.$j.']" value="'.$contents[$i].'" style="width:'.$length[$i].'px;"  lay-verify="required"  />&nbsp;';
                        $j++;
                    }
                    if ($k == 0) {
                        $str .= '<td><input type="button" value="+" id="getAtr" onClick="fun()"></td><br></span>';
                    }else{
                        $str .= '<td><input type="button" value="-" id="getAtr" onClick="getDel(this)"></td><br></span>';
                    }
                }
                $this->assign('html',$str);
            }


            $this->assign('num',$j);
            $this->assign('configuration',$arr);
            $this->assign('detail',$detail);
            $this->display('add');
        }
    }

    function del(){
        $id = I('post.id');
        $res = D('ApiProduct')->where(array('id' => $id))->delete();
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }
}
